<?php

namespace app\admin\logic;

use app\common\model\mysql\AccountModel;
use app\common\model\mysql\GroupModel;
use app\common\service\ExpireTimeService;
use app\common\service\MenuService;
use app\common\service\RedisKeyService;
use app\common\facade\encrypt\Password;
use app\common\logic\BaseLogic;
use think\facade\Cache;
use think\facade\Cookie;

class LoginLogic extends BaseLogic
{
    public function index($request)
    {

        $token = Cookie::get('token');

        if (!empty(Cache::exists($token))) {
            return redirect(config('admin.host') . '/admin/index');
        }
        return view('Login/login');
    }

    public function save($request)
    {
        $input = $request->param();

        $account = AccountModel::getOne(['name' => $input['name'], 'status' => 1]);
        if (empty($account)) {
            return $this->responseError('账号不存在');
        }

        if (!Password::checkPassword($account->password, $input['password'])) {
            return $this->responseError('密码错误');
        }

        $token = RedisKeyService::loginToken($account['mobile'] . '&' . time());

        $this->afterLogin($account, $token);
        Cookie::set('token', $token, ExpireTimeService::loginTime());
        return $this->responseSuccess('登录成功', compact('token'));
    }

    /**
     * 登录之后的步骤
     */
    protected function afterLogin($account, $token)
    {
        // 账号
        $info['id'] = $account->id;
        $info['name'] = $account->name;
        $info['headimg'] = $account->headimg;
        $info['group_ids'] = $account->group_ids;
        $info['mobile'] = $account->mobile;
        $info['project_ids'] = $account->project_ids;
        // 权限
        $groupRule = [];
        $groupIds = $account->group_ids;
        $groupInfos = GroupModel::field('rules')->whereIn('id', $groupIds)->select()->toArray();

        foreach ($groupInfos as $group) {
            $rulesArr = explode(',', $group['rules']);
            $groupRule = array_unique(array_merge($groupRule, $rulesArr));
            if (in_array('*', $groupRule)) {
                $groupRule = ['*'];
            }
        }

        $info['rules'] = $groupRule;
        $info['menu_html'] = MenuService::menuTree([2 => implode(',', $groupRule)]);
        $info['token'] = $token;
        Cache::set($token, $info, ExpireTimeService::loginTime());
    }

    public function quit($request)
    {
        $token = Cookie::get('token');
        Cache::delete($token);
        return $this->responseSuccess('退出登录成功');
    }

    public function error($request)
    {
        $input = $request->param();
        $code = $input['code'];
        $msg = $input['msg'];
        $desc = $input['desc'];
        return view('Login/error', compact('code', 'msg', 'desc'));
    }

}